import { View, Text, Button, Input, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import { useState } from 'react'
import { useAppContext } from '../../../store'
import { formatPrice } from '../../../utils'

import './index.scss'

export default function GuestMenu() {
  const { state, dispatch } = useAppContext()
  const { currentUser, dishes, categories, cart } = state
  const [selectedCategory, setSelectedCategory] = useState('all')
  const [searchKeyword, setSearchKeyword] = useState('')

  // 调试信息 - 只在开发环境显示
  if (process.env.NODE_ENV === 'development') {
    console.log('GuestMenu 组件加载')
    console.log('当前用户:', currentUser)
    console.log('菜品数量:', dishes.length)
    console.log('分类数量:', categories.length)
  }

  const getCategoryName = (categoryId: string) => {
    const category = categories.find(cat => cat.id === categoryId)
    return category?.name || '未分类'
  }

  // 过滤菜品
  const filteredDishes = dishes.filter(dish => {
    // 检查菜品是否匹配选中的分类
    const matchesCategory = selectedCategory === 'all' || 
                          dish.category === selectedCategory || 
                          getCategoryName(dish.category) === selectedCategory
                          
    // 检查菜品是否匹配搜索关键词
    const matchesSearch = searchKeyword === '' || 
                         dish.name.toLowerCase().includes(searchKeyword.toLowerCase()) ||
                         dish.description.toLowerCase().includes(searchKeyword.toLowerCase())
                         
    return matchesCategory && matchesSearch && dish.available
  })

  // 购物车总价
  const cartTotal = cart.reduce((total, item) => total + item.totalPrice, 0)
  const cartItemCount = cart.reduce((count, item) => count + item.quantity, 0)

  const handleAddToCart = (dish: any) => {
    const cartItem = {
      dishId: dish.id,
      dishName: dish.name,
      price: dish.price,
      quantity: 1,
      totalPrice: dish.price
    }
    dispatch({ type: 'ADD_TO_CART', payload: cartItem })
    Taro.showToast({ title: '已添加到购物车', icon: 'success' })
  }

  const handleViewCart = () => {
    Taro.navigateTo({ url: '/pages/guest/cart/index' })
  }

  const handleViewOrders = () => {
    Taro.navigateTo({ url: '/pages/guest/orders/index' })
  }

  const handleViewProfile = () => {
    Taro.navigateTo({ url: '/pages/guest/profile/index' })
  }

  const handleLogout = () => {
    dispatch({ type: 'LOGOUT' })
    Taro.reLaunch({ url: '/pages/index/index' })
  }

  return (
    <View className='guest-menu'>
      <View className='header'>
        <View className='header-left'>
          <View className='user-info'>
            <Text className='welcome'>欢迎，{currentUser?.name}</Text>
            <Text className='points'>积分: {currentUser?.points}</Text>
          </View>
        </View>
        <Button className='logout-btn' onClick={handleLogout}>退出</Button>
      </View>

      <View className='search-section'>
        <Input
          className='search-input'
          placeholder='搜索菜品...'
          value={searchKeyword}
          onInput={(e) => setSearchKeyword(e.detail.value)}
        />
      </View>

      <View className='category-tabs'>
        <View 
          className={`category-tab ${selectedCategory === 'all' ? 'active' : ''}`}
          onClick={() => setSelectedCategory('all')}
        >
          <Text>全部</Text>
        </View>
        {categories.map(category => (
          <View 
            key={category.id}
            className={`category-tab ${selectedCategory === category.id || selectedCategory === category.name ? 'active' : ''}`}
            onClick={() => setSelectedCategory(category.name)}
          >
            <Text>{category.name}</Text>
          </View>
        ))}
      </View>

      <View className='dishes-grid'>
        {filteredDishes.map(dish => (
          <View key={dish.id} className='dish-card'>
            <View className='dish-image'>
              <Image 
                src={dish.image || '/assets/images/default-dish.png'} 
                className='dish-img'
                mode='aspectFill'
              />
            </View>
            <View className='dish-info'>
              <Text className='dish-name'>{dish.name}</Text>
              <Text className='dish-desc'>{dish.description}</Text>
              <Text className='dish-category'>{getCategoryName(dish.category)}</Text>
              <View className='dish-footer'>
                <Text className='dish-price'>{formatPrice(dish.price)}</Text>
                <Button 
                  className='add-btn'
                  onClick={() => handleAddToCart(dish)}
                >
                  加入购物车
                </Button>
              </View>
            </View>
          </View>
        ))}
        {filteredDishes.length === 0 && (
          <View className='empty-state'>
            <Text className='empty-text'>暂无菜品</Text>
          </View>
        )}
      </View>

      {cartItemCount > 0 && (
        <View className='cart-fab' onClick={handleViewCart}>
          <View className='cart-icon'>🛒</View>
          <View className='cart-badge'>{cartItemCount}</View>
          <Text className='cart-total'>{formatPrice(cartTotal)}</Text>
        </View>
      )}

      {/* 底部导航栏 */}
      <View className='bottom-nav'>
        <View className='nav-item active' onClick={() => {}}>
          <Text className='nav-icon'>🍽️</Text>
          <Text className='nav-text'>菜单</Text>
        </View>
        <View className='nav-item' onClick={handleViewCart}>
          <Text className='nav-icon'>🛒</Text>
          <Text className='nav-text'>购物车</Text>
          {cartItemCount > 0 && (
            <View className='nav-badge'>{cartItemCount}</View>
          )}
        </View>
        <View className='nav-item' onClick={handleViewOrders}>
          <Text className='nav-icon'>📋</Text>
          <Text className='nav-text'>订单</Text>
        </View>
        <View className='nav-item' onClick={handleViewProfile}>
          <Text className='nav-icon'>👤</Text>
          <Text className='nav-text'>我的</Text>
        </View>
      </View>
    </View>
  )
} 